/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hongyan.page;


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.border.BevelBorder;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;


/**
 * 分页状态条
 * 用法如下：
 * class StatusBar extends AbstractStatusBar {
 *
 * @Override public String getTableName() {
 * // TODO Auto-generated method stub
 * // 组装全部查询语句
 * String sql = "select * from ...";
 * return sql;
 * }
 * @Override public void fillToTable(PageInfo pageInfo) {
 * // TODO Auto-generated method stub
 * //得到当前页查询语句
 * String cursql = pageInfo.getCurQuerySQL();
 * //利用当前页查询语句cursql做你自己的事情，如：查询出的数据填充到table
 * List list=query(cursql);
 * table.clear();
 * table.addAll(list);
 * }
 * }
 */

abstract public class AbstractStatusBar extends JPanel implements ActionListener {

    /**
     * 每页显示多少条
     */
    Integer[] pageSizeArr = new Integer[]{10, 50, 100};
    //    Box statusBarLeft;
    //    JLabel actionStatus;
    JButton previous;
    JButton next;
    JButton first;
    JButton last;
    JLabel statusLabel;
    JComboBox pageSizeComb = null;
    JTextField pageNoText;
    JButton go;
    private final static int H_BUT_PAD = 5;
    private PageInfo pageInfo;

    public AbstractStatusBar() {
        this(new PageInfo());
    }

    public AbstractStatusBar(PageInfo pageInfo) {
        super();
        this.pageInfo = pageInfo;
        this.setBorder(BorderFactory.createEmptyBorder(3, 0, 0, 0));
        this.setLayout(new BorderLayout());
//        Box statusBox = Box.createHorizontalBox();
        JPanel statusBox = new JPanel();
        statusBox.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
        // Left status area
        statusBox.add(Box.createRigidArea(new Dimension(10, 22)));
        previous = ButtonUtil.makeNavigationButton(null, "previous", "上一页", "上一页", this);
        next = ButtonUtil.makeNavigationButton(null, "next", "下一页", "下一页", this);
        first = ButtonUtil.makeNavigationButton(null, "first", "首页", "首页", this);
        last = ButtonUtil.makeNavigationButton(null, "last", "末页", "末页", this);

        pageSizeComb = new JComboBox(pageSizeArr) {

            @Override
            public Dimension getMaximumSize() {
                return new Dimension(1000, getPreferredSize().height);
            }
        };

        pageSizeComb.setActionCommand("changePageSize");
        pageSizeComb.setSelectedItem(new Integer(pageInfo.getPageSize()));
        pageSizeComb.addActionListener(this);

        pageNoText = new JTextField(10) {

            @Override
            protected Document createDefaultModel() {
                return new IntDocument();
            }

            class IntDocument extends PlainDocument {

                @Override
                public void insertString(int offs, String str, AttributeSet a)
                        throws BadLocationException {
                    if (str == null) {
                        return;
                    }
                    str = str.replaceAll("[^\\d]", "");
                    super.insertString(offs, str, a);
                }
            }

            @Override
            public Dimension getMaximumSize() {
                return new Dimension(1000, getPreferredSize().height);
            }
        };
        pageNoText.setActionCommand("go");
        pageNoText.addActionListener(this);

        go = ButtonUtil.makeNavigationButton(null, "go", "GO", "GO", this);


        statusLabel = new JLabel("找到" + pageInfo.getTotalSize() + "条记录, 显示 " + pageInfo.getCurFirst() + " 到 " + pageInfo.getCurLast() + " ,当前第" + (pageInfo.getCurPage()) + "页 , 共" + (pageInfo.getTotalPage()) + "页");
        statusLabel.setFont(new Font("宋体", Font.PLAIN, 12));
        Box pageSizePanel = Box.createHorizontalBox();
        pageSizePanel.add(new JLabel(" 每页显示"));
        pageSizePanel.add(pageSizeComb);
        pageSizePanel.add(new JLabel("条记录 "));

        Box goPanel = Box.createHorizontalBox();
        goPanel.add(new JLabel("跳转到第"));
        goPanel.add(pageNoText);
        goPanel.add(new JLabel("页"));
        goPanel.add(go);
        goPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
        statusBox.add(statusLabel);
        statusBox.add(Box.createHorizontalGlue());
        statusBox.add(first);
        statusBox.add(Box.createHorizontalStrut(H_BUT_PAD));
        statusBox.add(previous);
        statusBox.add(Box.createHorizontalStrut(H_BUT_PAD));
        statusBox.add(next);
        statusBox.add(Box.createHorizontalStrut(H_BUT_PAD));
        statusBox.add(last);
        statusBox.add(Box.createHorizontalStrut(H_BUT_PAD));
        statusBox.add(pageSizePanel);

        statusBox.add(goPanel);


        //</snip>
        this.add(statusBox);

        initButtonStatus();

    }
    /*
     * 设置按钮状态
     */

    private void initButtonStatus() {
        first.setEnabled(!pageInfo.isFirst());
        previous.setEnabled(!pageInfo.isFirst());
        next.setEnabled(!pageInfo.isLast());
        last.setEnabled(!pageInfo.isLast());
    }

    final public void loadData() {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                loading();

            }
        });
    }

    /**
     * 开始查询加载
     * pageInfo.setQuerySQL(sql);
     * pageInfo.setTotalSize(BaseDAO.getInstance().count(pageInfo.getCountSQL()));
     * pageInfo.setCurSize(BaseDAO.getInstance().count(pageInfo.getCurCountSQL()));
     */
    final private void loading() {
        initPageInfo();
        query();
    }

    /**
     * 设置pageInfo
     */
    final private void initPageInfo() {
        String sql = "select * from " + getTableName();
        pageInfo.setQuerySQL(sql);
        pageInfo.setTotalSize(BaseDAO.getInstance().count(pageInfo.getCountSQL()));
    }

    /**
     * 组装查询SQL
     * 可重写
     *
     * @return
     */
    abstract public String getTableName();

    /**
     * 填充表格
     * 可 重写
     */
    abstract public void fillToTable(PageInfo pageInfo);
    /*
     * 查询
     */

    final public void query() {
        pageInfo.setCurSize(BaseDAO.getInstance().count(pageInfo.getCurCountSQL()));//设置当前页记录数
        fillToTable(pageInfo);
        finished();
    }
    /*
     * 查询完成
     */

    final private void finished() {
        initButtonStatus();
        statusLabel.setText("找到" + pageInfo.getTotalSize() + "条记录, 显示 " + pageInfo.getCurFirst() + " 到 " + pageInfo.getCurLast() + " ,当前第" + (pageInfo.getCurPage()) + "页 共" + (pageInfo.getTotalPage()) + "页");

        /*this.revalidate();
        this.validate();
        this.invalidate();
        this.updateUI();*/
    }

    public void setPageInfo(PageInfo pageInfo) {
        this.pageInfo = pageInfo;
    }

    public PageInfo getPageInfo() {
        return pageInfo;
    }


    @Override
    public void actionPerformed(ActionEvent ae) {

        String command = ae.getActionCommand();
        if ("next".equals(command)) {
            pageInfo.next();
        } else if ("previous".equals(command)) {
            pageInfo.previous();
        } else if ("first".equals(command)) {
            pageInfo.goFirst();
        } else if ("last".equals(command)) {
            pageInfo.goLast();
        } else if ("go".equals(command)) {
            if (this.pageNoText.getText() != null && !"".equals(this.pageNoText.getText().trim())) {
                pageInfo.go(Integer.parseInt(this.pageNoText.getText().trim()));
                this.pageNoText.setText("");
            }

        } else if ("changePageSize".equals(command)) {
            pageInfo.setPageSize(Integer.parseInt(this.pageSizeComb.getSelectedItem().toString()));
        }

        if (pageInfo.getQuerySQL() != null) {
            this.query();
        }

    }
}
